package com.market.cash.pro

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import com.market.cash.CashRootApps
import com.market.cash.base.BaseActivity
import com.market.cash.databinding.CashLicenseViewBinding
import com.market.cash.http.IHttpCallback
import com.market.cash.utils.CashRootAesUtil
import com.market.cash.utils.CashRootImageUtil
import com.market.cash.utils.dialog.CashRootTipsDialog
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.event.CashRootEventHelper
import com.market.cash.utils.event.CashRootSubscriber
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.log.CashRootLog
import com.market.cash.utils.log.JsonFormat
import com.market.network.OkHttp
import com.market.network.callback.StringCallback
import com.market.network.model.Response
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/16 10:32
 * @Annotation：
 */
abstract class ProActivity: BaseActivity(), CashRootSubscriber,IProView {

    var errorDialog: CashRootTipsDialog? = null

    override fun getAct(): ProActivity {
        return this
    }

    override fun onStart() {
        super.onStart()
        CashRootApps.app.publisher.register(this)
    }

    /**
     * 错误提示
     */
    fun showErrorTipsDialog(tips: String,eventRemark: String = ""){
        if (errorDialog == null){
            errorDialog = CashRootTipsDialog(this,eventRemark,object : CashRootTipsDialog.IDialogCallback{
                override fun onClick(view: View?) {

                }
            })
        }
        if (errorDialog!!.isShowing){
            return
        }
        errorDialog!!.show()
        errorDialog!!.isDoubleButton(false)
        errorDialog!!.setTipsText(tips)
    }

    /**
     * post
     */
    fun doPostAction(httpUrl: String,params: JSONObject,callback: IHttpCallback){
        val aesParams = CashRootAesUtil.encryptDefault(params.toString())
        CashRootLog.e("HttpUrl：  $httpUrl")
        CashRootLog.e("HttpParams： $params")
        CashRootLog.e("HttpParams AES：  $aesParams")

        OkHttp.post<String>(httpUrl) // 请求方式和请求url
            .tag(this) // 请求的 tag, 主要用于取消对应的请求
            .upString(aesParams)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    val body = response.body()
                    if (response.code() != 200 || body == null || body.isEmpty()){
                        val errorObj = JSONObject()
                        errorObj.put("errorCode",response.code())
                        errorObj.put("errorMsg",response.message())
                        callback.onRequestError(errorObj)
                        return
                    }

                    val result = CashRootAesUtil.decryptDefault(body)
                    if (result.isNotEmpty()){
                        Thread { CashRootLog.i(JsonFormat.format(result)) }.start()
                        val data = JSONObject(result)
                        callback.onRequestSuccess(data)
                    } else {
                        val errorObj = JSONObject()
                        errorObj.put("errorCode",-1)
                        errorObj.put("errorMsg","http request error $result")
                        callback.onRequestError(errorObj)
                    }
                }

                override fun onError(response: Response<String>) {
                    val errorObj = JSONObject()
                    errorObj.put("errorCode",response.code())
                    errorObj.put("errorMsg",response.message())
                    callback.onRequestError(errorObj)
                }
                override fun onFinish() {
                    callback.onRequestFinish()
                }
            })
    }

    /**
     * 牌照信息View
     */
    fun initCashRootLicenseView(): View{
        val licenseInfo = CashRootCustomConfigsHelper.getCashRootLicenseInfo()
        if (licenseInfo != null){
            val binding = CashLicenseViewBinding.inflate(layoutInflater)
            CashRootImageUtil.instance.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))

            val desc = licenseInfo.optString("desc")
            val companyName = licenseInfo.optString("companyName")
            val showText = "$desc $companyName"
            val spString = SpannableString(showText)
            val start = showText.indexOf(companyName)
            spString.setSpan(ForegroundColorSpan(Color.parseColor("#000000")), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            binding.textLicenseInfo.text = spString
            return binding.root
        }
        return View(this)
    }

    /**
     * 发送事件通知
     */
    fun publishEventData(eventData: CashRootEventData){
        CashRootApps.app.publisher.publish(eventData)
    }

    /**
     * 处理订阅事件
     */
    override fun onCashRootEvent(event: CashRootEventData) {
    }

    /**
     * 添加埋点
     */
    fun addCashRootEventPoint(eventName: String, eventRemark: String = "") {
        CashRootEventHelper.addCashRootRequestEventAction(eventName,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        OkHttp.getInstance().cancelTag(this)
        CashRootApps.app.publisher.detach(this)
    }
}